package com.zzyl.nursing.service.impl;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.db.PageResult;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.R;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.DeviceDataDto;
import com.zzyl.nursing.dto.IotHealthDto;
import com.zzyl.nursing.dto.MemberUserAddDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.service.IElderService;
import com.zzyl.nursing.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.IFamilyMemberElderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;

import static net.sf.jsqlparser.parser.feature.Feature.insert;

/**
 * 客户老人关联Service业务层处理
 *
 * @author ruoyi
 * @date 2025-10-19
 */
@Service
public class FamilyMemberElderServiceImpl extends ServiceImpl<FamilyMemberElderMapper, FamilyMemberElder> implements IFamilyMemberElderService {
    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;

    @Autowired
    private IElderService elderService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    /**
     * 新增绑定家人
     */
    @Override
    public void addBindFamily(MemberUserAddDto memberUserAddDto) {
        Elder elder = getElderId(memberUserAddDto.getIdCard());
        Long elderId = elder.getId();
        //当前小程序登录用户id
        Long id = UserThreadLocal.get();
        //获取家属

        FamilyMemberElder familyMemberElder = new FamilyMemberElder();
        familyMemberElder.setFamilyMemberId(id);
        familyMemberElder.setElderId(elderId);
        familyMemberElderMapper.insert(familyMemberElder);
    }

    /**
     * 根据身份证号查询老人信息
     */
    private Elder getElderId(String idcard) {
        LambdaQueryWrapper<Elder> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Elder::getIdCardNo, idcard);
        return elderService.getOne(lqw);
    }

    /**
     * 查询老人家属列表
     *
     * @return
     */
    @Override
    public List<FamilyMemberElderVo> getFamilyList() {
        List<FamilyMemberElder> familyMemberElders = list();
        ArrayList<FamilyMemberElderVo> familyMemberElderVos = new ArrayList<>();
        for (FamilyMemberElder familyMemberElder : familyMemberElders) {
            FamilyMemberElderVo fVo = BeanUtil.toBean(familyMemberElder, FamilyMemberElderVo.class);
            //根据elderId查老人name
            Elder elder = elderService.getById(familyMemberElder.getElderId());
            fVo.setElderName(elder.getName());
            familyMemberElderVos.add(fVo);
        }

        return familyMemberElderVos;
    }

    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private RoomMapper roomMapper;

    /**
     * 查看已绑定家人列表（分页查询）
     */
    @Override
    public List<FamilyMemberElderPageVo> getFamilyListPage(Integer pageNum, Integer pageSize) {
        //开启分页
        PageHelper.startPage(pageNum, pageSize);
        //在threadLocal中获取当前登录用户在数据库中存储的主键id
        Long id = UserThreadLocal.get();
        List<FamilyMemberElderPageVo> familyMemberElderVos = familyMemberElderMapper.selectFamilyMemberPage(id);


        //取出所有绑定的elderId
        List<Long> elderIds = familyMemberElderVos.stream().map(FamilyMemberElderPageVo::getElderId).collect(Collectors.toList());
        //根据老人id查询老人表，名字，头像，床位编号，房间名称
        List<Elder> elders = elderMapper.selectBatchIds(elderIds);
        //根据老人id查询设备表，老人id等于设备绑定位置
        List<Device> devices = deviceMapper.selectDevice(elderIds);

        for (FamilyMemberElderPageVo familyMemberElderVo : familyMemberElderVos) {

            for (Elder elder : elders) {
                if (Objects.equals(familyMemberElderVo.getElderId(), elder.getId())) {
                    familyMemberElderVo.setName(elder.getName());
                    familyMemberElderVo.setImage(elder.getImage());
                    familyMemberElderVo.setBedNumber(elder.getBedNumber());
                    //这里还得根通过bedNumber查床位表，得到roomId，再通过roomId查房间表，得到房间类型名称
                    Long roomId = bedMapper.selectRoomIdByBedNumber(elder.getBedNumber());
                    String typeName = roomMapper.selectRoomTypeNameByRoomId(roomId);
                    familyMemberElderVo.setTypeName(typeName);
                }
            }
            for (Device device : devices) {
                String elderId = String.valueOf(familyMemberElderVo.getElderId());
                if (Objects.equals(device.getBindingLocation(), elderId)) {
                    familyMemberElderVo.setIotId(device.getIotId());
                    familyMemberElderVo.setDeviceName(device.getDeviceName());
                    familyMemberElderVo.setProductKey(device.getProductKey());
                }
            }
        }

        return familyMemberElderVos;
    }

    /**
     * 查看健康数据
     */
    @Override
    public DataVo QueryDevicePropertyStatus(IotHealthDto iotHealthDto) {
        //查出设备的IotId
        LambdaQueryWrapper<Device> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Device::getDeviceName,iotHealthDto.getDeviceName())
                .eq(Device::getProductKey,iotHealthDto.getProductKey());
        Device device = deviceMapper.selectOne(lqw);
        String iotId = device.getIotId();
        //根据iotID从redis中查询最新的设备数据
        String json = (String) redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, iotId);
        //反序列化
        List<DeviceData> deviceDataList = JSONUtil.toList(json, DeviceData.class);
        DataVo dataVo = new DataVo();
        ListVo listVo = new ListVo();
        PropertyStatusInfoVo propertyStatusInfoVo1 = new PropertyStatusInfoVo();
        List<PropertyStatusInfoVo> propertyStatusInfo = new ArrayList<>();
        for (DeviceData deviceData : deviceDataList) {
            PropertyStatusInfoVo propertyStatusInfoVo = new PropertyStatusInfoVo();
            propertyStatusInfoVo.setDataType(deviceData.getLocationType());
            propertyStatusInfoVo.setIdentifier(deviceData.getFunctionId());
            propertyStatusInfoVo.setName(deviceData.getProductName());
            propertyStatusInfoVo.setTime(deviceData.getAlarmTime());
            propertyStatusInfoVo.setValue(deviceData.getDataValue());
            //单位
            propertyStatusInfoVo.setUnit(null);
            propertyStatusInfo.add(propertyStatusInfoVo);
        }
        listVo.setPropertyStatusInfo(propertyStatusInfo);
        dataVo.setList(listVo);

        return dataVo;
    }

    @Autowired
    private IDeviceDataService deviceDataService;
    /**
     * 按天统计查询指标数据
     */
    @Override
    public List<DataTimeDataValueVo> queryDeviceDataListByDay(DeviceDataDto deviceDataDto) {
//        Long startTime = deviceDataDto.getStartTime();
//        Long endTime = deviceDataDto.getEndTime();
//        //转换成LocalDateTime
//        LocalDateTime startDateTime = Instant.ofEpochMilli(startTime).atZone(ZoneId.systemDefault()).toLocalDateTime();
//        LocalDateTime endDateTime = Instant.ofEpochMilli(endTime).atZone(ZoneId.systemDefault()).toLocalDateTime();
//        FamilyMemberDeviceData familyMemberDeviceData = new FamilyMemberDeviceData();
//        familyMemberDeviceData.setFunctionId(deviceDataDto.getFunctionId());
//        familyMemberDeviceData.setIotId(deviceDataDto.getIotId());
//        familyMemberDeviceData.setEndTime(deviceDataDto.);
//        familyMemberDeviceData.setStartTime(startDateTime);

        //查询设备数据
        List<DeviceData> list = deviceDataMapper.selectDeviceDataDay(deviceDataDto);
        List<DataTimeDataValueVo> dataTimeDataValueVoList = new ArrayList<>();
        for (DeviceData deviceData : list) {
            DataTimeDataValueVo dataTimeDataValueVo = new DataTimeDataValueVo();
            dataTimeDataValueVo.setDataTime(deviceData.getAlarmTime());
            dataTimeDataValueVo.setDataValue(deviceData.getDataValue());
            dataTimeDataValueVoList.add(dataTimeDataValueVo);
        }
        return dataTimeDataValueVoList;
    }


    /**
     * 按周统计查询指标数据
     * @param deviceDataDto
     * @return
     */
    @Override
    public List<DataTimeDataValueVo> queryDeviceDataListByWeek(DeviceDataDto deviceDataDto) {
        //查询设备数据
        List<DeviceData> list = deviceDataMapper.selectDeviceDataWeek(deviceDataDto);
        List<DataTimeDataValueVo> dataTimeDataValueVoList = new ArrayList<>();
        for (DeviceData deviceData : list) {
            DataTimeDataValueVo dataTimeDataValueVo = new DataTimeDataValueVo();
            dataTimeDataValueVo.setDataTime(deviceData.getAlarmTime());
            dataTimeDataValueVo.setDataValue(deviceData.getDataValue());
            dataTimeDataValueVoList.add(dataTimeDataValueVo);
        }
        return dataTimeDataValueVoList;
    }
}
